#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>

char command_line[1024];//命令行数组
char* myargv[64];

int main()
{
    while(1)
    {
        //输入提示符：
        printf("用户名@主机名 当前路径# ");
        fflush(stdout);

        //获取用户输入，回车结束\n
        char* s = fgets(command_line, sizeof(command_line)-1, stdin);
        assert(s != NULL);

        command_line[strlen(command_line)-1] = 0;
        
        //ls -a -l -i --> "ls","-a","-l","-i"
        myargv[0] = strtok(command_line," ");
        int i = 1;
        //while(myargv[i++] = strtok(NULL, " "));
        while(1)
    //    {
    //        //如果没有字串了，则strtok->NULL myargv[end] = NULL;
    //        myargv[i] = strtok(NULL, " ");
    //    
    //        if(myargv[i] == NULL)
    //            break;

    //        i++;
    //    }
        if(myargv[0] && strcmp(myargv[0],"cd") == 0)
        {
            if(myargv[1])
                chdir(myargv[1]);

            continue;
        }
//条件编译，测试上面的分离字符串是否成功
#ifdef DEBUG 
        int j = 0;
        for(j  = 0; myargv[j]; ++j)
        {
            printf("argv[%d]:%s\n",j,myargv[j]);
        }
#endif

        pid_t id = fork();
        assert(id != -1);
        if(id == 0)
        {
            execvp(myargv[0],myargv);
            exit(1);
        }
        waitpid(id, NULL, 0);
    }
    return 0;
}
